module.exports = {


  friendlyName: 'View vulnerability list',


  description: 'Display "Vulnerability list" page.',



  inputs: {

    minSeverity: {
      description: 'Optional filter to only get vulnerabilities whose `severity` is >= the specified value.',
      type: 'number',
      defaultsTo: 0,
    },

    maxSeverity: {
      description: 'Optional filter to only get vulnerabilities whose `severity` is <= the specified value.',
      type: 'number',
      defaultsTo: 10,
    },

    sortBy: {
      description: 'An optional facet to sort vulnerabilities by.',
      type: 'string',
      isIn: [
        'cveId',
        'severity',
        'hasKnownExploit',
        'publishedAt',
        'resolvedAt',
      ],
      defaultsTo: 'publishedAt'
    },

    sortDirection: {
      type: 'string',
      isIn: [
        'ASC',
        'DESC',
      ],
      defaultsTo: 'DESC'
    },

    page: {
      description: 'The zero-indexed page number.',
      type: 'number',
      defaultsTo: 0
    },

    teamApid: {
      description: 'The ID of the Team to filter by, or 0 to only include hosts with no team, or undefined to not filter by any team.',
      type: 'number',
    }

  },



  exits: {

    success: {
      viewTemplatePath: 'pages/dashboard/vulnerability-list'
    },

  },


  fn: async function (inputs) {

    let ENTRIES_PER_PAGE = 40;

    let totalVulnerabilities = await Vulnerability.count();

    // Send an empty array of vulnerabilities to start with, this way, we can reduce the inital load time, and use the
    // page's _getVulnerabilities() function to get the first page of vulnerabilities while showing them a loading screen.
    let vulnerabilities = [];
    // FUTURE: this won't work for deployments with hundreds of thousands of hosts.
    let hostRecords = await Host.find();

    let allTeams = [];
    let teamNameByApid = {};
    for(let host of hostRecords){
      teamNameByApid[host.teamApid] = host.teamDisplayName;
      let team = {
        name: host.teamDisplayName ? host.teamDisplayName : 'No team',
        id: host.teamApid,
      };
      allTeams.push(team);
    }
    let teamsToDisplay = _.uniq(allTeams, 'id');

    // Send the applied filters down to the page.
    let filters = inputs;

    // Respond with view.
    return {
      filters,
      teamsToDisplay,
      teamNameByApid,
      totalVulnerabilities,
      vulnerabilities,
      ENTRIES_PER_PAGE,
      fleetBaseUrl: sails.config.custom.fleetBaseUrl
    };

  }


};
